import 'dart:async';
import 'package:loxen/routes/routes.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/viewmode/login_view_model.dart';
import 'package:provider/provider.dart';

class BindingPhonePage extends StatefulWidget {
  final String openid;
  final String platform;

  const BindingPhonePage({Key key, this.openid, this.platform})
      : super(key: key);

  @override
  _BindingPhonePageState createState() => _BindingPhonePageState();
}

class _BindingPhonePageState extends State<BindingPhonePage> {
  Timer _countdownTimer;
  String _codeCountdownStr = '获取验证码';
  int _countdownNum = 59;

  //焦点
  FocusNode _focusPhone = new FocusNode();
  FocusNode _focusVode = new FocusNode();

  TextEditingController _userPhoneController = new TextEditingController();
  TextEditingController _userCodeController = new TextEditingController();

  //表单状态
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  var _isShowClearPhone = false; //是否显示输入框尾部的
  var _isShowClearVode = false; //是否显示输入框尾部的

  @override
  void initState() {
    //设置焦点监听
    _focusPhone.addListener(_focusNodeListener);
    _focusVode.addListener(_focusNodeListener);
    _userPhoneController.addListener(() {
      print(_userPhoneController.text);
      errorMobile = null;
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userPhoneController.text.length > 0) {
        _isShowClearPhone = true;
      } else {
        _isShowClearPhone = false;
      }
      setState(() {});
    });
    _userCodeController.addListener(() {
      print(_userCodeController.text);
      errorCode = null;
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userCodeController.text.length > 0) {
        _isShowClearVode = true;
      } else {
        _isShowClearVode = false;
      }
      setState(() {});
    });
    super.initState();
  }

  @override
  void dispose() {
    // 移除焦点监听
    _focusPhone.removeListener(_focusNodeListener);
    _focusVode.removeListener(_focusNodeListener);
    _userPhoneController.dispose();
    _userCodeController.dispose();
    _countdownTimer?.cancel();
    _countdownTimer = null;
    super.dispose();
  }

  // 监听焦点
  Future<Null> _focusNodeListener() async {
    if (_focusPhone.hasFocus) {
      print("手机号框获取焦点");
      // 取消用户名框焦点状态
      _focusVode.unfocus();
    }
    if (_focusVode.hasFocus) {
      print("验证码框获取焦点");
      (_formKey.currentState as FormState).reset();

      // 取消用户名框焦点状态
      _focusPhone.unfocus();
    }
  }

  String validateUserPassword(value) {
    // 正则匹配用户名
    if (value.isEmpty) {
      return '密码不能为空!';
    }
    return null;
  }

  String validateUserMobile(value) {
    // 正则匹配手机号
    RegExp exp = RegExp(
        r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
    if (value.isEmpty) {
      return '手机号不能为空!';
    } else if (!exp.hasMatch(value)) {
      return '请输入正确手机号';
    }
    return null;
  }

  /**
   * 验证密码
   */
  String validateCode(value) {
    if (value.isEmpty) {
      return '验证码不能为空';
    }
    return null;
  }

  var errorMobile;
  var errorPwd;
  var errorCode;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('绑定手机号'),
          centerTitle: true,
          brightness: Brightness.dark,
          leading: GestureDetector(
            onTap: () {
              Navigator.pop(context);
              Navigator.of(context).pushNamed(Routes.login_page);
            },
            child: Icon(Icons.arrow_back_ios),
          ),
        ),
        body: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onPanDown: (_) {
              FocusScope.of(context).requestFocus(FocusNode());
            },
          child: Stack(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.fromLTRB(94.w, 50.h, 94.w, 0),
                child: Form(
                  key: _formKey, //设置globalKey，用于后面获取FormState
                  child: Column(
                    children: <Widget>[
                      new TextFormField(
                        style:
                        TextStyle(color: Color(0xFF000000), fontSize: 28.sp),
                        controller: _userPhoneController,
                        focusNode: _focusPhone,
                        //设置键盘类型
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          WhitelistingTextInputFormatter.digitsOnly,
                          //限制只允许输入数字
                          LengthLimitingTextInputFormatter(11),
                          //限制输入长度不超过8位
                        ],
                        decoration: InputDecoration(
                          errorText: errorMobile,
                          errorStyle: TextStyle(
                              color: Color(0xFFFE0600), fontSize: 20.sp),
                          hintText: "手机号 (请输入11位手机号)",
                          hintStyle: TextStyle(
                              fontSize: 28.sp, color: Color(0xFF999999)),
//                        尾部添加清除按钮
                          suffixIcon: (_isShowClearPhone)
                              ? IconButton(
                            icon: Icon(
                              Icons.cancel,
                              size: 27.sp,
                            ),
                            onPressed: () {
                              // 清空输入框内容
                              _userPhoneController.clear();
                            },
                          )
                              : null,
                        ),
                        validator: validateUserMobile,
                      ),
                      new TextFormField(
                          style: TextStyle(
                              color: Color(0xFF000000), fontSize: 28.sp),
                          controller: _userCodeController,
                          focusNode: _focusVode,
                          inputFormatters: [
//                    WhitelistingTextInputFormatter(RegExp("[a-z,A-Z,0-9]")),      //限制只允许输入字母和数字
                            WhitelistingTextInputFormatter.digitsOnly,
                            //限制只允许输入数字
                            LengthLimitingTextInputFormatter(6),
                            //限制输入长度不超过8位
                          ],
                          keyboardType: TextInputType.number,
                          decoration: InputDecoration(
                              errorText: errorCode,
                              errorStyle: TextStyle(
                                  color: Color(0xFFFE0600), fontSize: 20.sp),
                              suffixIcon: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  (_isShowClearVode)
                                      ? IconButton(
                                    icon: Icon(
                                      Icons.cancel,
                                      size: 27.sp,
                                    ),
                                    onPressed: () {
                                      // 清空输入框内容
                                      _userCodeController.clear();
                                    },
                                  )
                                      : Text(""),
                                  Builder(
                                      builder: (context) => FlatButton(
                                        onPressed: sendCode() ? send : null,
                                        child: Text(_codeCountdownStr),
                                      ))
                                ],
                              ),
                              hintText: "请输入验证码",
                              hintStyle: TextStyle(
                                  fontSize: 28.sp, color: Color(0xFF999999))),
                          //验证码验证
                          validator: validateCode),
                    ],
                  ),
                ),
              ),
              Positioned(
                left: 94.w,
                top: 815.h,
                child: Container(
                  width: 559.w,
                  height: 96.h,
                  color: Color(0xFF0CABCB),
                  child: new FlatButton(
                    child: new Text(
                      '注册',
                      style: TextStyle(fontSize: 30.sp, color: Color(0xFFF7F8F8)),
                    ),
                    onPressed: () {
                      if (_formKey.currentState.validate()) {
                        context.read<LoginViewModel>().thirdPartRegister(
                            widget.platform,
                            widget.openid,
                            _userPhoneController.text,
                            _userCodeController.text, onSuccess: () {
                          Navigator.popUntil(
                              context, ModalRoute.withName(Routes.main_page));
                        }, onFail: (error) {
                          setState(() {
                            errorCode = error;
                          });


                          _focusVode.unfocus();
                        });
                      } else {
                        _focusPhone.unfocus();
                        _focusVode.unfocus();
                      }
                    },
                  ),
                ),
              ),
            ],
          )),
          );
  }

  void reGetCountdown() {
    setState(() {
      if (_countdownTimer != null) {
        return;
      }
      // Timer的第一秒倒计时是有一点延迟的，为了立刻显示效果可以添加下一行。
      _codeCountdownStr = '${_countdownNum--}重新获取';
      _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
        setState(() {
          if (_countdownNum > 0) {
            _codeCountdownStr = '${_countdownNum--}重新获取';
          } else {
            _codeCountdownStr = '获取验证码';
            _countdownNum = 59;
            _countdownTimer.cancel();
            _countdownTimer = null;
          }
        });
      });
    });
  }

  void decideError(String T) {
    setState(() {
      if (T.length > 1) {
        errorMobile = T;
        return errorMobile;
      }
    });
  }

  void send() {
    context.read<LoginViewModel>().code(_userPhoneController.text, "4",
        onSuccess: () {
      reGetCountdown();
    }, onFail: (error) {
      decideError(error);
    });
  }

  bool sendCode() {
    if (validateUserMobile(_userPhoneController.text) == null &&
        _countdownNum == 59) {
      return true;
    } else {
      errorMobile = validateUserMobile(_userPhoneController.text);
      return false;
    }
  }
}
